'
经验场景
'

extends Node2D

@onready var collision_shape_2d: CollisionShape2D = $Area2D/CollisionShape2D
@onready var sprite: Sprite2D = $Sprite2D


func _ready() -> void:
	$Area2D.area_entered.connect(on_area_entered)
	pass

#触发收集时转向玩家
func tween_collect(percent: float, start_position: Vector2) -> void:
	var player = get_tree().get_first_node_in_group("player")
	if player == null:
		return
	self.global_position = start_position.lerp(player.global_position,percent)
	var direction_from_start = player.global_position - start_position
	var target_rotation = direction_from_start.angle() + TAU / 4
	self.rotation = lerp_angle(self.rotation,target_rotation,1-exp(-2 * get_process_delta_time()))
	pass

#被收集时销毁
func collect() -> void:
	GameEvents.emit_experience_collected(1)
	self.queue_free()
	pass

#禁止碰撞
func disable_collision() -> void:
	collision_shape_2d.disabled = true
	pass

#玩家进入碰撞区域，开始被收集
func on_area_entered(_area:Area2D) -> void:
	Callable(disable_collision).call_deferred()
	var tween = create_tween()
	tween.set_parallel()
	tween.tween_method(tween_collect.bind(self.global_position), 0.0, 1.0, .5)\
	.set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_BACK)
	tween.tween_property(sprite, "scale", Vector2.ZERO, .1).set_delay(.4)
	tween.chain()
	tween.tween_callback(collect)
	$RanAudComponent.play_random()
	pass
